package com.sinder.campus_prophet.service.general.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinder.campus_prophet.core.global.ResponseMessage;
import com.sinder.campus_prophet.entity.general.TbWxUser;
import com.sinder.campus_prophet.entity.jwgl.TbJwglInfo;
import com.sinder.campus_prophet.entity.jwgl.TbTerm;
import com.sinder.campus_prophet.mapper.general.TbWxUserMapper;
import com.sinder.campus_prophet.mapper.jwgl.TbJwglInfoMapper;
import com.sinder.campus_prophet.mapper.jwgl.TbTermMapper;
import com.sinder.campus_prophet.service.general.TbWxUserService;
import com.sinder.campus_prophet.service.general.bean.dto.RegisterUserDto;
import com.sinder.campus_prophet.service.general.bean.dto.UpUserInfoDto;
import com.sinder.campus_prophet.service.general.bean.vo.UserInfoVo;
import com.sinder.campus_prophet.utils.UniqueCodeUtils;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
* @author AS
* @description 针对表【tb_wx_user(微信用户授权表)】的数据库操作Service实现
* @createDate 2023-03-15 23:10:16
*/
@Service
@Slf4j
public class TbWxUserServiceImpl extends ServiceImpl<TbWxUserMapper, TbWxUser>
    implements IService<TbWxUser> , TbWxUserService {

    private final TbWxUserMapper wxUserMapper;

    private final TbJwglInfoMapper jwglInfoMapper;

    private final TbTermMapper tbTermMapper;

    public TbWxUserServiceImpl(TbWxUserMapper wxUserMapper, TbJwglInfoMapper jwglInfoMapper, TbTermMapper tbTermMapper) {
        this.wxUserMapper = wxUserMapper;
        this.jwglInfoMapper = jwglInfoMapper;
        this.tbTermMapper = tbTermMapper;
    }

    /**
     * 授权注册登录
     * @param registerUser
     * @return
     */
    @Override
    public ResponseMessage registerUser(RegisterUserDto registerUser) {
        // 校验是否已经存在用户
        UserInfoVo user = wxUserMapper.getUserInfo(registerUser.getWxOpenId());
        if (user != null) {
            return ResponseMessage.createBySuccess("用户已存在", user);
        }
        TbWxUser tbWxUser = new TbWxUser();
        BeanUtils.copyProperties(registerUser, tbWxUser);
        // 转换emoji表情包
        if (tbWxUser.getUserNick() != null) {
            tbWxUser.setUserNick(EmojiParser.parseToAliases(tbWxUser.getUserNick()));
        }
        // 生成个人唯一标识
        tbWxUser.setUserCode(UniqueCodeUtils.uniqueCode());
        // 默认头像
        tbWxUser.setHeadUrl("https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0");
        // 设定默认角色权限 1：管理员、2：学生
        tbWxUser.setRoleId(2);
        tbWxUser.setIsDelete(0);
        tbWxUser.setCreateTime(new Date());
        // 添加注册用户
        try {
            int row = wxUserMapper.insert(tbWxUser);
            if (row <= 0)
                return ResponseMessage.createByErrorMessage("用户注册异常，请联系管理员");
        } catch (DuplicateKeyException e) {
            log.warn("用户{}重复注册异常", registerUser.getWxOpenId());
            return ResponseMessage.createByErrorMessage("用户重复注册");
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(tbWxUser, userInfoVo);
        // 默认未绑定教务系统
        userInfoVo.setIsBindJwgl(false);
        return ResponseMessage.createBySuccess("注册成功，返回用户信息", userInfoVo);
    }

    /**
     * 获取用户个人标识
     * @param openId
     * @return
     */
    @Override
    public ResponseMessage getUserCode(String openId) {
        String userCode = wxUserMapper.getUserCode(openId);
        if (userCode == null) {
            throw new NullPointerException("用户不存在，请联系管理员");
        }
        return ResponseMessage.createBySuccess("用户标识", userCode);
    }

    /**
     * 用户更新个人信息
     * @param userDto
     * @return
     */
    @Override
    public boolean updateUserInfo(UpUserInfoDto userDto) {
        TbWxUser wxUser = new TbWxUser();
        wxUser.setBingCode(userDto.getBingCode());
        if (userDto.getUserNick() != null) {
            wxUser.setUserNick(EmojiParser.parseToAliases(userDto.getUserNick()));
        }
        wxUser.setUserPhone(userDto.getUserPhone());
        wxUser.setHeadUrl(userDto.getHeadUrl());
        QueryWrapper<TbWxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wx_open_id", userDto.getWxOpenId());
        int row = wxUserMapper.update(wxUser, queryWrapper);
        return row > 0;
    }

    /**
     * 获取用户信息
     * @param openId
     * @return
     */
    @Override
    public ResponseMessage getUserInfo(String openId) {
        UserInfoVo userInfoVo = wxUserMapper.getUserInfo(openId);
        if (userInfoVo == null) {
            return ResponseMessage.createByErrorMessage("用户不存在，请先注册");
        }
        userInfoVo.setTemp(true);
        // 判断是否已经绑定了教务账号密码
        QueryWrapper<TbJwglInfo> jwglInfoQueryWrapper = new QueryWrapper<>();
        jwglInfoQueryWrapper.eq("wx_open_id", openId);
        List<TbJwglInfo> jwglInfos = jwglInfoMapper.selectList(jwglInfoQueryWrapper);
        // 默认没绑定
        userInfoVo.setIsBindJwgl(false);
        if (userInfoVo.getUserNick() != null) {
            userInfoVo.setUserNick(EmojiParser.parseToUnicode(userInfoVo.getUserNick()));
        }
        if (jwglInfos.size() >= 1) {
            userInfoVo.setIsBindJwgl(true);
        }
        // 规避用户隐私开关
        TbTerm temp = tbTermMapper.selectById(2);
        userInfoVo.setTemp(temp != null && Boolean.parseBoolean(temp.getStartTime()));
        return ResponseMessage.createBySuccess("用户信息", userInfoVo);
    }
}




